package com.siwei.mes.service.laboratory.impl;


import com.alibaba.fastjson.JSON;
import com.siwei.mes.common.util.UploadFlagUtils;
import com.siwei.mes.config.UidUtils;
import com.siwei.mes.entity.DownloadLaboratoryEntity;
import com.siwei.mes.entity.ShxhSynchronizedata;
import com.siwei.mes.entity.UploadLaboratoryEntity;
import com.siwei.mes.entity.experiment.CheckBatchConfig;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.laboratory.WtConsign;
import com.siwei.mes.entity.laboratory.WtConsignWithSample;
import com.siwei.mes.entity.laboratory.WtSample;
import com.siwei.mes.entity.system.TemperatureAndHumidity;
import com.siwei.mes.entity.system.TestProjectInfo;
import com.siwei.mes.enums.*;
import com.siwei.mes.mapper.ShxhSynchronizedataMapper;
import com.siwei.mes.mapper.experiment.CheckBatchConfigMapper;
import com.siwei.mes.mapper.laboratory.DataDefUcLaboratoryMapper;
import com.siwei.mes.mapper.laboratory.WTConsignMapper;
import com.siwei.mes.mapper.laboratory.WTConsignWithSampleMapper;
import com.siwei.mes.mapper.laboratory.WTSampleMapper;
import com.siwei.mes.mapper.system.TestProjectInfoMapper;
import com.siwei.mes.service.experiment.ExperimentService;
import com.siwei.mes.service.laboratory.DownloadLaboratoryService;
import com.siwei.mes.service.laboratory.FinishLaboratoryService;
import com.siwei.mes.service.laboratory.UploadAndDownloadAssociationService;
import com.siwei.mes.service.laboratory.UploadLaboratoryService;
import com.siwei.mes.service.system.TemperatureAndHumidityService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * @author chenmaolin
 */
@Service
public class UploadAndDownloadAssociationlServiceImpl implements UploadAndDownloadAssociationService {
    private static final Logger log = LoggerFactory.getLogger("laboratory");

    @Value("${deptName}")
    private String experimentDept;
    @Resource
    private UploadLaboratoryService uploadLaboratoryService;
    @Resource
    private ShxhSynchronizedataMapper shxhSynchronizedataMapper;
    @Resource
    private FinishLaboratoryService finishLaboratoryService;
    @Resource
    private DownloadLaboratoryService downloadLaboratory;
    @Resource
    private ExperimentService experimentService;
    @Resource
    private WTConsignWithSampleMapper wtConsignWithSampleMapper;
    @Resource
    private WTConsignMapper wtConsignMapper;
    @Resource
    private WTSampleMapper wtSampleMapper;
    @Resource
    private TestProjectInfoMapper testProjectInfoMapper;
    @Resource
    private CheckBatchConfigMapper checkBatchConfigMapper;
    @Resource
    private TemperatureAndHumidityService temperatureAndHumidityService;
    @Resource
    private DataDefUcLaboratoryMapper dataDefUcLaboratoryMapper;

    @Override
    public void uploadLaboratory(UploadLaboratoryEntity entity) {
        log.info("正在处理上传协会数据，入参：【{}】", JSON.toJSON(entity));

        assertTrue(entity == null || entity.getExperimentId() == null || entity.getExperimentId().isEmpty(), "上传上海协会操作数据，试验台账id不允许为空！");
        List<String> experimentId = entity.getExperimentId();
        Integer uploadState = entity.getUploadState();
        for (String val : experimentId) {

            //根据品控台账id 查询上海协会sampleNo
            Experiment experiment = experimentService.loadById(Long.parseLong(val));

            assertTrue(experiment == null, "未查询到品控对应的台账信息！台账id :" + val);

            /**这里只判断不是混凝土类型的*/
            if (!experiment.getExperimentType().equals(MaterialsEnum.CONCRETE.getCode())
                    && !experiment.getExperimentStatus().equals(ExperimentStatusEnum.IN_TEST.getCode())) {
                log.error("品控台账编码为{} 状态不是试验中，不能上传协会！", experiment.getId());
                continue;
            }

            //如果为原材料
            List<String> stringList = new ArrayList<>();
            stringList.add(val);

            UploadLaboratoryEntity UploadLaboratoryEntity = new UploadLaboratoryEntity().setExptId(experiment.getId()).setExperimentId(stringList);

            //查询上传协会状态
            List<ShxhSynchronizedata> list = shxhSynchronizedataMapper.getList(new ShxhSynchronizedata().setExperimentId(experiment.getId()));
            log.error("查询协会上传数据结果{} 品控台账编码为{}", list, experiment.getId());
            try {

                //如果为混凝土
                if (MaterialsEnum.CONCRETE.getCode().equals(experiment.getExperimentType())) {
                    //如果为自动上传 的混凝土  则加一条机制
                    // 1、抗压试验：
                    //如果上一条委托（根据生成时间倒序排序）协会委托编号及样品编号为空时，则不上传，当用户点击手动上传补完数据后，才允许继续自动上传   对应的协会是1108
                    //2、抗渗试验：
                    //如果上一条委托（根据生成时间倒序排序）协会委托编号及样品编号为空时，则不上传，当用户点击手动上传补完数据后，才允许继续自动上传     1110
                    if (uploadState != null && uploadState == 1) {
                        if (experiment.getEntrustExperiment() != null && experiment.getEntrustExperiment().contains("抗压强度")) {
                            List<Experiment> hntKyExperiment = entity.getHntExperiment();
                            if (hntKyExperiment == null || hntKyExperiment.isEmpty() || hntKyExperiment.size() == 0) {
                                log.error("自动上传失败，上级传入最近两条委托数据为空!");
                                return;
                            }
                            //如果倒数第一条的值和当前上传的委托相同 则取倒数第二条
                            if (hntKyExperiment.get(0).getExperimentNo().equals(experiment.getExperimentNo())) {
                                Experiment kyExperiment = hntKyExperiment.get(1);
                                //如果关联数据为空 则停止自动上传
                                if (StringUtils.isBlank(kyExperiment.getSampleId()) && StringUtils.isBlank(kyExperiment.getConsignId())) {
                                    log.error("根据委托时间查询出当前倒数第一条委托为：" + hntKyExperiment.get(0).getExperimentNo());
                                    log.error("根据委托时间查询出当前倒数第二条委托为：" + hntKyExperiment.get(1).getExperimentNo());
                                    log.error("当前上传委托编号为：" + experiment.getExperimentNo() + ",与倒数第一条值相同，所以取值为倒数第二条委托！");
                                    log.error("自动上传失败，请手动上传，根据委托时间倒序查询到抗压强度委托：" + kyExperiment.getExperimentNo() + "，还未进行上传，已停止自动上传!");
                                    return;
                                }
                            } else {
                                Experiment kyExperiment = hntKyExperiment.get(0);
                                //如果关联数据为空 则停止自动上传
                                if (StringUtils.isBlank(kyExperiment.getSampleId()) && StringUtils.isBlank(kyExperiment.getConsignId())) {
                                    log.error("根据委托时间查询出当前倒数第一条委托为：" + hntKyExperiment.get(0).getExperimentNo());
                                    log.error("根据委托时间查询出当前倒数第二条委托为：" + hntKyExperiment.get(1).getExperimentNo());
                                    log.error("当前上传委托编号为：" + experiment.getExperimentNo() + ",取值为倒数第一条委托！");
                                    log.error("自动上传失败，请手动上传，根据委托时间倒序查询到抗压强度委托：" + kyExperiment.getExperimentNo() + "，还未进行上传，已停止自动上传!");
                                    return;
                                }
                            }
                        } else if (experiment.getEntrustExperiment() != null && experiment.getEntrustExperiment().contains("抗渗等级")) {
                            List<Experiment> hntKsExperiment = entity.getHntExperiment();
                            if (hntKsExperiment == null || hntKsExperiment.isEmpty() || hntKsExperiment.size() == 0) {
                                log.error("自动上传失败，上级传入最近两条委托数据为空!");
                                return;
                            }
                            //如果倒数第一条的值和当前上传的委托相同 则取倒数第二条
                            if (hntKsExperiment != null && hntKsExperiment.get(0).getExperimentNo().equals(experiment.getExperimentNo())) {
                                Experiment ksExperiment = hntKsExperiment.get(1);
                                //如果关联数据为空 则停止自动上传
                                if (StringUtils.isBlank(ksExperiment.getSampleId()) && StringUtils.isBlank(ksExperiment.getConsignId())) {
                                    log.error("根据委托时间查询出当前倒数第一条委托为：" + hntKsExperiment.get(0).getExperimentNo());
                                    log.error("根据委托时间查询出当前倒数第二条委托为：" + hntKsExperiment.get(1).getExperimentNo());
                                    log.error("当前上传委托编号为：" + experiment.getExperimentNo() + ",与倒数第一条值相同，所以取值为倒数第二条委托！");
                                    log.error("自动上传失败，请手动上传，根据委托时间倒序查询到抗渗等级委托：" + ksExperiment.getExperimentNo() + "，还未进行上传，已停止自动上传!");
                                    return;
                                }
                            } else {
                                Experiment ksExperiment = hntKsExperiment.get(0);
                                //如果关联数据为空 则停止自动上传
                                if (StringUtils.isBlank(ksExperiment.getSampleId()) && StringUtils.isBlank(ksExperiment.getConsignId())) {
                                    log.error("根据委托时间查询出当前倒数第一条委托为：" + hntKsExperiment.get(0).getExperimentNo());
                                    log.error("根据委托时间查询出当前倒数第二条委托为：" + hntKsExperiment.get(1).getExperimentNo());
                                    log.error("当前上传委托编号为：" + experiment.getExperimentNo() + ",取值为倒数第一条委托！");
                                    log.error("自动上传失败，请手动上传，根据委托时间倒序查询到抗渗等级委托：" + ksExperiment.getExperimentNo() + "，还未进行上传，已停止自动上传!");
                                    return;
                                }
                            }
                        }
                    }

                    if (list == null || list.isEmpty()) {

                        //生成台账 + 样品
                        uploadLaboratoryService.generateLedger(UploadLaboratoryEntity);

                        //试验结果
                        finishLaboratoryService.finishLaboratory(UploadLaboratoryEntity);

                        return;
                    }

                    ShxhSynchronizedata synchronizedata = list.get(0);


                    //台账 + 样品
                    uploadLaboratoryService.generateLedger(UploadLaboratoryEntity);

                    //试验结果
                    finishLaboratoryService.finishLaboratory(UploadLaboratoryEntity);


                    //置空失败原因
                    if (synchronizedata.getReason() != null && !synchronizedata.getReason().isEmpty()) {
                        synchronizedata.setReason("");
                        shxhSynchronizedataMapper.updateByPrimaryKeySelective(synchronizedata);
                    }


                } else {


                    if (list == null || list.isEmpty()) {
                        //进料
                        uploadLaboratoryService.incomingMaterials(UploadLaboratoryEntity);
                        //取样
                        uploadLaboratoryService.samplingOperation(UploadLaboratoryEntity);
                        //生成台账
                        uploadLaboratoryService.generateLedger(UploadLaboratoryEntity);

                        //试验结果
                        finishLaboratoryService.finishLaboratory(UploadLaboratoryEntity);

                        return;
                    }

                    ShxhSynchronizedata synchronizedata = list.get(0);

                    if (synchronizedata.getImportId() == null || synchronizedata.getImportId().isEmpty()) {
                        //进料
                        uploadLaboratoryService.incomingMaterials(UploadLaboratoryEntity);
                    } else {
                        uploadLaboratoryService.updateIncomingMaterials(UploadLaboratoryEntity, synchronizedata.getImportId());
                    }

                    if (synchronizedata.getSampleId() == null || synchronizedata.getSampleId().isEmpty()) {
                        //取样
                        uploadLaboratoryService.samplingOperation(UploadLaboratoryEntity);
                    }

                    //生成台账
                    uploadLaboratoryService.generateLedger(UploadLaboratoryEntity);

                    //试验结果
                    finishLaboratoryService.finishLaboratory(UploadLaboratoryEntity);


                    //置空失败原因
                    if (synchronizedata.getReason() != null && !synchronizedata.getReason().isEmpty()) {
                        synchronizedata.setReason("");
                        shxhSynchronizedataMapper.updateByPrimaryKeySelective(synchronizedata);
                    }

                }

            } catch (Exception e) {
                log.error("上传协会失败：" + e.getMessage(), e);

                //查询上传协会状态

                ShxhSynchronizedata shxhInfo = shxhSynchronizedataMapper.selectByExperimentIdOne(experiment.getId());
                if (shxhInfo == null) {
                    ShxhSynchronizedata synchronizedata = new ShxhSynchronizedata()
                            .setReason("上传协会失败：" + e.getMessage()).setExperimentId(experiment.getId());
                    shxhSynchronizedataMapper.insertSelective(synchronizedata);
                } else {
                    shxhInfo.setReason("上传协会失败：" + e.getMessage());
                    shxhSynchronizedataMapper.updateByPrimaryKeySelective(shxhInfo);
                }
            }

        }


    }

    @Override
    public void downloadLaboratory(DownloadLaboratoryEntity entity) {
        log.info("正在处理下载协会数据：{}", JSON.toJSONString(entity));
        assertTrue(entity == null || entity.getExperimentId() == null || entity.getExperimentId().isEmpty(), "上传上海协会操作数据，试验台账id不允许为空！");
        List<String> experimentId = entity.getExperimentId();

        for (String val : experimentId) {

            //根据品控台账id 查询上海协会sampleNo
            Experiment experiment = experimentService.loadById(Long.parseLong(val));

            assertTrue(experiment == null, "未查询到品控对应的台账信息！台账id :" + val);


            //如果为原材料
            List<String> stringList = new ArrayList<>();
            stringList.add(val);

            UploadLaboratoryEntity UploadLaboratoryEntity = new UploadLaboratoryEntity().setExptId(experiment.getId()).setExperimentId(stringList);

            //查询上传协会状态
            List<ShxhSynchronizedata> list = shxhSynchronizedataMapper.getList(new ShxhSynchronizedata().setExperimentId(experiment.getId()));

            try {

                //下载协会试验结果信息
                downloadLaboratory.downloadLaboratory(UploadLaboratoryEntity);


                //置空失败原因
                ShxhSynchronizedata synchronizedata = list.get(0);

                if (synchronizedata.getDownloadReason() != null && !synchronizedata.getDownloadReason().isEmpty()) {
                    synchronizedata.setDownloadReason("");
                    shxhSynchronizedataMapper.updateByPrimaryKeySelective(synchronizedata);
                }


            } catch (Exception e) {
                log.error("下载协会失败：" + e.getMessage());

                ShxhSynchronizedata shxhInfo = shxhSynchronizedataMapper.selectByExperimentIdOne(experiment.getId());
                if (shxhInfo == null) {
                    ShxhSynchronizedata synchronizedata = new ShxhSynchronizedata()
                            .setDownloadReason("下载协会失败：" + e.getMessage()).setExperimentId(experiment.getId());
                    shxhSynchronizedataMapper.insertSelective(synchronizedata);
                } else {
                    shxhInfo.setDownloadReason("下载协会失败：" + e.getMessage());
                    shxhSynchronizedataMapper.updateByPrimaryKeySelective(shxhInfo);
                }
            }
        }
    }

    @Override
    public void insetWtConsignWithSample(String beginDate, String endDate) {

        if (StringUtils.isBlank(beginDate) || StringUtils.isBlank(endDate)) {
            return;
        }

        log.info("开始时间 ：" + beginDate + ",结束时间 ：" + endDate);
        Experiment exp = new Experiment().setExperimentType(MaterialsEnum.CONCRETE.getCode()).setCheckType(CheckEnum.BATCH.getCode()).setBeginTime(beginDate).setComTime(endDate);
        List<Experiment> experimentList = experimentService.getAll(exp);

        log.info("查询出混凝土台账数量为 ：" + experimentList.size());

        List<Long> list = new ArrayList<>();

        for (Experiment experiment : experimentList) {
            //协会委托为空 则不处理
            if (StringUtils.isBlank(experiment.getConsignId()) || StringUtils.isBlank(experiment.getSampleId()) || StringUtils.isBlank(experiment.getEntrustExperiment())) {
                continue;
            }

            if (experiment.getEntrustExperiment().contains("抗压强度")) {
                list.add(experiment.getId());
            }

        }

        if (list.isEmpty()) {
            return;
        }

        List<ShxhSynchronizedata> mapperList = shxhSynchronizedataMapper.getList(new ShxhSynchronizedata().setExperimentIdList(list));


        for (ShxhSynchronizedata synchronizedata : mapperList) {

            if (StringUtils.isBlank(synchronizedata.getConsignId()) || StringUtils.isBlank(synchronizedata.getSampleId())) {
                continue;
            }

            List<WtConsignWithSample> wtConsignWithSample = wtConsignWithSampleMapper.findWtConsignWithSample(new WtConsignWithSample().setSampleId(synchronizedata.getSampleId()).setConSignId(synchronizedata.getConsignId()));

            //新增
            if (wtConsignWithSample.isEmpty()) {
                WtConsign consignId = wtConsignMapper.findConsignId(synchronizedata.getConsignId());

                if (consignId == null) {
                    log.info("查询协会台账信息为空,台账id ：" + synchronizedata.getConsignId() + "样品id :" + synchronizedata.getSampleId());
                    continue;
                }


                log.info("开始新增关联表信息,台账id ：" + synchronizedata.getConsignId() + "样品id :" + synchronizedata.getSampleId() + "任务单id:" + consignId.getProduceId());

                //新增关联表
                WtConsignWithSample withSample = new WtConsignWithSample();
                withSample.setConSignId(synchronizedata.getConsignId());
                withSample.setSampleId(synchronizedata.getSampleId());
                withSample.setProduceIndexId(consignId.getProduceId());
                String wtConsignWithSampleUploadFlag = UploadFlagUtils.CtoGB_Num(synchronizedata.getSampleId(), "z", new Date(), "");
                withSample.setUploadFlag(wtConsignWithSampleUploadFlag);

                wtConsignWithSampleMapper.insertWtConsignWithSample(withSample);
            }
        }


    }

    @Override
    public void synchronizeData(String beginDate, String endDate) {
        if (StringUtils.isBlank(beginDate) || StringUtils.isBlank(endDate)) {
            return;
        }
        log.info("同步协会历史混凝土抗渗/抗折台账信息开始...");
        log.info("开始时间 ：" + beginDate + ",结束时间 ：" + endDate);


        try {
            List<WtSample> wtSampleList = wtSampleMapper.findWTSampleListByTime(beginDate, endDate);

            /**获取所有混凝土相关的试验项目*/
            Map<String, TestProjectInfo> testProjectInfoMap = this.getTestProjectInfoMap();

            for (WtSample wtSample : wtSampleList) {
                //根据协会台账id + 样品id 查询是否已经上传过
                List<ShxhSynchronizedata> mapperList = shxhSynchronizedataMapper.getList(new ShxhSynchronizedata().setConsignId(wtSample.getConSignId()).setSampleId(wtSample.getSampleNo()));
                //不为空说明已经上传过的 则不处理
                if (mapperList != null && !mapperList.isEmpty()) {
                    continue;
                }

                /**委托试验名称*/
                Set<String> entrustExperimentSet = new HashSet<>();
                /**试验项目code集合*/
                Set<String> testProjectCodeList = new HashSet<>();
                /**获取所有试验项目配置*/
                List<TestProjectInfo> testProjectInfoList = new ArrayList<>();


                if (StringUtils.isNotBlank(wtSample.getExamParameterCn()) && wtSample.getExamParameterCn().contains("抗渗等级")) {
                    String TEST_PROJECT_CODE = TestProjectEnum.CONCRETE_PARAM_KSDJ.getCode();

                    TestProjectInfo projectInfo = testProjectInfoMap.get(TEST_PROJECT_CODE);

                    testProjectInfoList.add(projectInfo);
                    testProjectCodeList.add(projectInfo.getTestCode());
                    entrustExperimentSet.add(projectInfo.getTestName());

                    String entrustExperiment = entrustExperimentSet.stream().map(String::valueOf).collect(Collectors.joining(","));
                    Experiment experiment = this.getExperimentInfoByItemOrderInfo(CheckEnum.BATCH.getCode(), entrustExperiment, testProjectCodeList, wtSample);

                } else if (StringUtils.isNotBlank(wtSample.getExamParameterCn()) && wtSample.getExamParameterCn().contains("抗折强度")) {

                }


            }


        } catch (Exception e) {
            log.error("同步协会历史混凝土抗渗/抗折台账信息失败：" + e.getMessage());
            throw new RuntimeException("同步协会历史混凝土抗渗/抗折台账信息失败：" + e.getMessage());
        }
    }

    @Override
    public void delDataDefaultUc(String sampleNo) {
        try {
            dataDefUcLaboratoryMapper.deleteDATA_DefaultUCBySampleNo(sampleNo);
        } catch (Exception e) {
            log.error("删除dataDefaultUc数据信息失败：" + e.getMessage());
            throw new RuntimeException("删除dataDefaultUc数据信息失败：" + e.getMessage());
        }
    }

    //生成抗渗台账
    public void genKsExperiment() {

    }


    public Experiment getExperimentInfoByItemOrderInfo(Integer checkType, String entrustExperiment, Set<String> testProjectCodeList, WtSample wtSample) {
        Experiment experiment = payloadExperiment(MaterialsEnum.CONCRETE.getCode(), wtSample);
        experiment.setEntrustExperiment(entrustExperiment);
        experiment.setCheckType(checkType);
        /**组装其它信息*/
        this.payloadOtherInfo(experiment, testProjectCodeList);
        return experiment;
    }

    public static Experiment payloadExperiment(Integer experimentType, WtSample wtSample) {
        Experiment experiment = new Experiment();
        experiment.setUpdateTime(new Date()).setCreateTime(new Date())
                .setIsDel(0).setExperimentNo(UidUtils.genNo(GenerateCodeEnum.EXPERIMENT.getCode()));
        experiment.setExperimentType(experimentType);
        experiment.setEntrustTime(wtSample.getMoldingDate());
        //experiment.setSampleLevel(entity.getTpz());
        //experiment.setMaterialsName(entity.getTpz());

        experiment.setBehalfNumber(wtSample.getDelegateQuan() == null ? 0 : Double.valueOf(wtSample.getDelegateQuan()));
        experiment.setEntrustReasonCode(EnturstReasonEnum.CJ.getCode());
        experiment.setEntrustReasonName(EnturstReasonEnum.CJ.getName());

        experiment.setEntrustPersonName("");
        if (StringUtils.isNotBlank(wtSample.getSampleStatus())) {
            //（0,待检，1已检，2在检）
            if ("0".equals(wtSample.getSampleStatus())) {
                experiment.setExperimentStatus(ExperimentStatusEnum.WAIT_ACCEPT.getCode());
            } else if ("1".equals(wtSample.getSampleStatus())) {
                experiment.setExperimentStatus(ExperimentStatusEnum.FINISH.getCode());
            } else if ("2".equals(wtSample.getSampleStatus())) {
                experiment.setExperimentStatus(ExperimentStatusEnum.IN_TEST.getCode());
            }

        }
        return experiment;
    }

    /**
     * 组装其它信息  试验依据、判断依据、仪器设备、最后一条含水率配置
     *
     * @param experiment          试验委托信息
     * @param testProjectCodeList 试验项目集合
     */
    public void payloadOtherInfo(Experiment experiment, Set<String> testProjectCodeList) {
        Integer checkType = experiment.getCheckType();//委托类型 1-快检 2-批检
        Integer projectCategory = experiment.getExperimentType();
        Set<String> experimentGistList = new HashSet<>();//试验依据集合
        Set<String> judgeGistList = new HashSet<>();//判断依据集合
        Set<String> entrustExperimentSet = new HashSet<>();//试验名称集合
        Set<String> equipmentNoList = new HashSet<>();//仪器设备

        experiment.setCuringMode("标准养护");
        /**如果委托部门为空就赋值系统参数配置的*/
        if (StringUtils.isBlank(experiment.getExperimentDept())) {
            experiment.setExperimentDept(experimentDept);
        }

        /**这里根据试验项目去查询配置的试验依据和判断依据  检查类型 1-快检 2-批检*/
        if (testProjectCodeList != null && !testProjectCodeList.isEmpty()) {
            if (CheckEnum.BATCH.getCode().equals(checkType)) {
                List<CheckBatchConfig> list = checkBatchConfigMapper.getList(new CheckBatchConfig().setTestProjectCodeList(testProjectCodeList).setProjectCategory(projectCategory));
                for (CheckBatchConfig config : list) {
                    if (StringUtils.isNotBlank(config.getExperimentGist())) {
                        List<String> experimentGist = Arrays.stream(config.getExperimentGist().split(";"))
                                .collect(Collectors.toList());
                        experimentGistList.addAll(experimentGist);
                    }
                    if (StringUtils.isNotBlank(config.getJudgeGist())) {
                        List<String> judgeGists = Arrays.stream(config.getJudgeGist().split(";"))
                                .collect(Collectors.toList());
                        judgeGistList.addAll(judgeGists);
                    }
                    if (StringUtils.isNotBlank(config.getEquipmentNo())) {
                        equipmentNoList.addAll(Arrays.asList(config.getEquipmentNo().split(";")));
                    }
                }
            }


            List<TestProjectInfo> testProjectInfoList = testProjectInfoMapper.selectByTestProjectCodeList(testProjectCodeList);
            for (TestProjectInfo testProjectInfo : testProjectInfoList) {
                entrustExperimentSet.add(testProjectInfo.getTestName());
            }
        }

        if (!equipmentNoList.isEmpty()) {
            String equipment = equipmentNoList.stream().map(String::valueOf).collect(Collectors.joining(";"));
            experiment.setEquipment(equipment);
        }

        /**委托试验*/
        if (!entrustExperimentSet.isEmpty()) {
            String entrustExperiment = entrustExperimentSet.stream().map(String::valueOf).collect(Collectors.joining(","));
            experiment.setEntrustExperiment(entrustExperiment);
        }

        /**试验依据*/
        if (!experimentGistList.isEmpty()) {
            String experimentGist = experimentGistList.stream().map(String::valueOf).collect(Collectors.joining(";"));
            experiment.setExperimentGist(experimentGist);
        }
        /**判断依据*/
        if (!judgeGistList.isEmpty()) {
            String judgeGist = judgeGistList.stream().map(String::valueOf).collect(Collectors.joining(";"));
            experiment.setJudgeGist(judgeGist);
        }

        /**获取最后一条含水率配置*/
        TemperatureAndHumidity lastInfo = temperatureAndHumidityService.getLastInfo(new TemperatureAndHumidity());
        if (lastInfo != null) {
            experiment.setTemperature(lastInfo.getTemperature());
            experiment.setHumidness(lastInfo.getHumidness());
        }
    }

    /**
     * 获取所有混凝土的试验项目  key:试验项目code   value:试验项目对象
     *
     * @return
     */
    private Map<String, TestProjectInfo> getTestProjectInfoMap() {
        List<TestProjectInfo> list = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(TestProjectTypeEnum.CONCRETE.getCode()));
        return list.stream().collect(Collectors.toMap(TestProjectInfo::getTestCode, obj -> obj));
    }
}
